let express = require('express');
let router = express.Router();
let jwt = require('../common/jwt')

let mongoose = require('mongoose')
mongoose.connect("mongodb://127.0.0.1:27017/auth");
mongoose.connection.on("connected", function () {
    console.log("mongodb connect success")
});
mongoose.connection.on("error", function () {
    console.log("1")
});
let groups = require('../models/groups')
let users = require('../models/users')


router.use(function (req, res, next) {
    if (req.path !== '/login') {
        let token = req.headers['x-access-token']
        let jwtData = jwt.verifyToken(token)
        if (jwtData.code === 401) {
            res.json({
                code: 401,
                msg: '没有该权限'
            })
            return
        } else {
            // console.info(userData)
            // if (req.path === '/pullUser') {
            //     groups.findOne({_id: userData.data.range}, {range: 1, _id: 0})
            //         .exec(function (err, data) {
            //             if (err) {
            //                 console.info(err)
            //                 res.json({
            //                     code: -1,
            //                     msg: '服务器错误，请刷新后重试'
            //                 })
            //                 return
            //             }
            //             console.info(data)
            //             next()
            //
            //         })
            // }else {
            //
            // }
            next()
        }
    } else {
        next()
    }

});

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

// 刷新页面重新获取菜单和更新token
router.post('/pullUser', function (req, res, next) {
    let token = req.headers['x-access-token']
    let userData = jwt.verifyToken(token)
    users.findOne({userName: userData.data.userName}, {__v: 0, _id: 0, password: 0})
        .populate({
            path: `groupId`,
            select: `-__v`
        })
        .exec(function (err, data) {
            if (err) {
                console.info(err)
                res.json({
                    code: -1,
                    msg: '服务器错误，请刷新后重试'
                })
                return
            }
            let token = jwt.signToken({
                userName: data.userName,
                range: data.groupId[0]._id
            })
            res.json({
                code: 0,
                data: {
                    groupId: {
                        groupName: data.groupId[0].groupName,
                        menuData: data.groupId[0].menuData,
                        range: data.groupId[0].range
                    },
                    userName: data.userName,
                    nikeName: data.nikeName
                },
                token: token
            })
        });
})

router.post('/login', function (req, res, next) {
    let userName = req.body.userName
    let password = req.body.password
    console.info(password)
    users.findOne({userName: userName, password: password}, {__v: 0, _id: 0, password: 0})
        .populate({
            path: `groupId`,
            select: `-__v`
        })
        .exec(function (err, data) {
            if (err) {
                res.json({
                    code: -1,
                    msg: '服务器错误，请刷新后重试'
                })
                return
            }
            if (!data) {
                res.json({
                    code: -1,
                    msg: '用户名或者密码错误'
                })
                return
            }
            let token = jwt.signToken({
                userName: data.userName,
                range: data.groupId[0]._id
            })
            res.json({
                code: 0,
                data: {
                    groupId: {
                        groupName: data.groupId[0].groupName,
                        menuData: data.groupId[0].menuData,
                        range: data.groupId[0].range
                    },
                    userName: data.userName,
                    nikeName: data.nikeName
                },
                token: token
            })
        });
})


router.use(function (req, res, next) {
    next()
})
// 添加成员
router.post('/addUser', function (req, res, next) {
    let userName = req.body.userName
    users.find({userName: userName}, function (err, data) {
        if (err) {
            console.info(err)
            res.json({
                code: -1,
                msg: '系统错误！'
            })
            return
        }
        if (data.length > 0) {
            res.json({
                code: -2,// 用户名以存在
                msg: '用户名以存在！'
            })
            return
        }
        let addUser = new users({
            userName: userName,
            password: req.body.password,
            nikeName: req.body.nikeName,
            groupId: req.body.groupId
        })
        addUser.save(function (err, docs) {
            if (err) {
                console.info(err)
                res.json({
                    code: -1,
                    msg: '系统错误！'
                })
                return
            }
            groups.update({_id: req.body.groupId}, {'$inc': {peopleNum: 1}}, function (err) {
                if (err) {
                    console.info(err)
                    res.json({
                        code: -1,
                        msg: '系统错误！'
                    })
                    return
                }
                res.json({
                    code: 1,
                    msg: '添加成功！'
                })
            })
        })
    })
})
//编辑成员
router.post('/editUser', function (req, res, next) {
    let id = req.body._id
    let userData = {
        userName: req.body.userName,
        password: req.body.password,
        nikeName: req.body.nikeName,
    }
    users.update({_id: id}, userData, function (err, docs) {
        if (err) {
            console.info(err)
            res.json({
                code: -1,
                msg: '系统错误！'
            })
            return
        }
        res.json({
            code: 1,
            msg: '操作成功！'
        })
    })
})
// 获取成员列表
router.post('/getMemberList', function (req, res, next) {
    let id = req.body.id
    users.find({groupId: id}, {__v: 0}, function (err, data) {
        if (err) {
            console.info(err)
            res.json({
                code: -1,
                msg: '系统错误！'
            })
            return
        }
        res.json({
            code: 0,
            data: data
        })
    })
})
// 删除成员
router.post('/memberDelete', function (req, res, next) {
    let id = req.body.id
    let groupId = req.body.groupId
    users.remove({_id: id}, function (err, docs) {
        if (err) {
            console.log(err);
            res.json({
                code: -1,
                msg: '系统错误！'
            })
            return
        }
        groups.update({_id: groupId}, {'$inc': {peopleNum: -1}}, function (err) {
            if (err) {
                console.info(err)
                res.json({
                    code: -1,
                    msg: '系统错误！'
                })
                return
            }
            res.json({
                code: 1,
                msg: '删除成功！'
            })
        })
    })
})
// 添加分组 或者修改
router.post('/addGroup', function (req, res, next) {
    let groupsData = req.body.data
    groups.update({_id: groupsData.id === '' ? mongoose.Types.ObjectId(null) : groupsData.id}, groupsData, {
        upsert: true,
        multi: true
    }, function (err, docs) {
        if (err) {
            console.info(err)
            res.json({
                code: -1,
                msg: '系统错误！'
            })
            return
        }
        res.json({
            code: 0,
            msg: '添加成功！'
        })
    })
})
// 组删除
router.post('/groupDelete', function (req, res, next) {
    let id = req.body.id
    groups.remove({_id: id}, function (err, docs) {
        if (err) {
            console.log(err);
            res.json({
                code: -1,
                msg: '系统错误！'
            })
            return
        }
        users.remove({groupId: id}, function (err, docs) {
            if (err) {
                console.log(err);
                res.json({
                    code: -1,
                    msg: '系统错误！'
                })
            }
            console.info(docs)
            res.json({
                code: 0,
                msg: '删除成功！'
            })
        })
    })
})
// 获取组列表
router.post('/getGroupList', function (req, res, next) {
    groups.find({groupName: {$ne: 'admin'}}, {_id: 1, groupName: 1, peopleNum: 1}, function (err, data) {
        if (err) {
            console.info(err)
            res.json({
                msg: '获取组信息失败，请刷新后重试',
                code: -1
            })
            return
        }
        res.json({
            data: data,
            code: 0
        })
    })
})
// 通过id获取组信息
router.post('/getGroupInfo', function (req, res, next) {
    let id = req.body.id
    groups.find({_id: id}, {groupName: 1, menuData: 1, range: 1, CheckedKey: 1}, function (err, data) {
        if (err) {
            console.info(err)
            res.json({
                msg: '获取组信息失败，请刷新后重试',
                code: -1
            })
            return
        }
        res.json({
            code: 0,
            data: data
        })
    })
})
module.exports = router;
